<?php

namespace App\Http\Controllers\Machine;

use App\Exceptions\BusinessException;
use App\Http\Controllers\Controller;
use App\Models\OrderGoodsViewModel;
use App\Models\OrderModel;
use App\Models\SpecModel;
use App\Models\SupplyModel;
use App\Models\UserModel;
use App\Utils\ApiResponse;
use App\Utils\VerifyRequestInput;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;

class SupplyController extends Controller
{
    use ApiResponse, VerifyRequestInput;

    /**
     * 获取开通代拿商家列表
     * @return JsonResponse
     */
    public function getSupplyUserList(): JsonResponse
    {
        $sids = [8, 89, 1177, 1537];
        $supplies = SupplyModel::whereIn('ID', $sids)->pluck('CName', 'ID');
        $list = [];
        $users = UserModel::whereIn('sid', $sids)->where('role', 'user')->select('id', 'sid', 'username')->get();
        foreach ($supplies as $sid => $sName) {
            $list[] = [
                'sid' => $sid,
                'sName' => $sName,
                'users' => array_values($users->where('sid', $sid)->toArray())
            ];
        }
        return $this->success($list);
    }

    /**
     * 获取商家代拿数据
     * 未拿货列表
     * @return JsonResponse
     * @throws BusinessException
     */
    public function getSupplyOrderGoods(): JsonResponse
    {
        $sid = $this->verifyId('sid');
        $collection = OrderGoodsViewModel::where('pay_status', 1)->where('refund_status', 0)->where('express_status', 1)->where('done_status', 0)
        ->where('sid', $sid)->get(['id', 'order_no', 'sid', 'goods_id', 'goods_sn', 'thumbnail', 'color', 'size', 'weight', 'price', 'goods_num',
                'goods_name', 'goods_remark', 'doned_at', 'tag', 'created_at', 'refund'])->groupBy('goods_id');
        $data = $this->formatCollection($collection, true);
        return $this->success($data);
    }

    /**
     * 格式化
     * @param $collection
     * @param $detail
     * @return array
     */
    private function formatCollection($collection, $detail): array
    {
        $data = [];
        foreach ($collection as $goods_id => $list) {
            if (count($list)) {
                $specs = $list->groupBy('goods_sn');
                $specList = [];
                // 同规格合并
                foreach ($specs as $sameSpecList) {
                    $sameSpecItem = $sameSpecList[0];
                    if ($sameSpecItem) {
                        $sameTotal = 0;
                        $tagTotal = 0;
                        $orderGoodsIds = [];
                        $orders = [];
                        $orderUserRemarks = OrderModel::whereIn('order_no', array_map(function ($o) {
                            return $o['order_no'];
                        }, $sameSpecList->toArray()))->pluck('remark', 'order_no')->toArray();
                        foreach ($sameSpecList as $v) {
                            $sameTotal += $v->goods_num;
                            $orderGoodsIds[] = $v->id;
                            if ($v->tag === '预先拿货')
                                $tagTotal += $v->goods_num;
                            $orders[] = [
                                'id' => $v->id,
                                'created_at' => (new Carbon($v->created_at))->toDateTimeString(),
                                'order_no' => $v->order_no, 'goods_remark' => $v->goods_remark,
                                'goods_num' => $v->goods_num,
                                'tag'       => $v->tag,
                                'refund'    => $v->refund,
                                'user_remark' => $orderUserRemarks[$v->order_no] ?? ''
                            ];
                        }
                        $sameSpecItem->tag_count = $tagTotal;
                        $sameSpecItem->thumbnail = SpecModel::where('goods_id', $goods_id)->where('color', $sameSpecItem->color)->where('thumbnail', '!=', '0')->value('thumbnail');
                        $sameSpecItem->goods_num = $sameTotal;
                        if ($detail) {
                            $sameSpecItem->ids = $orderGoodsIds;
                            $sameSpecItem->orders = $orders;
                        } else
                            $sameSpecItem->total = $sameTotal * $sameSpecItem->price;
                        $specList[] = $sameSpecItem;
                    }
                }
                $data[] = ['goods_id' => $list[0]['goods_id'], 'goods_name' => $list[0]['goods_name'], 'list' => $specList];
            }
        }
        return $data;
    }
}
